<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="第4章 ：混合对象“类” 本章要介绍和类相关的面相对象编程的知识。首先会介绍面相对象类的设计模式：实例化(instantiation)、继承(inheritance)、多态(polymorphism)。 但由于这些概念上无法直接对应到JavaScript的对象机制，因此很多JavaScript开发者使用了一些比如mixin等解决方法来实现。4.1 类理论 类&#x2F;继承，或者说面向对象，是用来描述代码的">
<meta property="og:type" content="article">
<meta property="og:title" content="《你不知道的JavaScript(上)》S02E04">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E04/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:description" content="第4章 ：混合对象“类” 本章要介绍和类相关的面相对象编程的知识。首先会介绍面相对象类的设计模式：实例化(instantiation)、继承(inheritance)、多态(polymorphism)。 但由于这些概念上无法直接对应到JavaScript的对象机制，因此很多JavaScript开发者使用了一些比如mixin等解决方法来实现。4.1 类理论 类&#x2F;继承，或者说面向对象，是用来描述代码的">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-12-01T14:26:46.000Z">
<meta property="article:modified_time" content="2020-12-01T15:07:14.687Z">
<meta property="article:author" content="William Leung">
<meta property="article:tag" content="你不知道的JavaScript">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E04/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>《你不知道的JavaScript(上)》S02E04 | 汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%AC%AC4%E7%AB%A0-%EF%BC%9A%E6%B7%B7%E5%90%88%E5%AF%B9%E8%B1%A1%E2%80%9C%E7%B1%BB%E2%80%9D"><span class="nav-number">1.</span> <span class="nav-text">第4章 ：混合对象“类”</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-%E7%B1%BB%E7%90%86%E8%AE%BA"><span class="nav-number">1.0.1.</span> <span class="nav-text">4.1 类理论</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#4-1-1-%E2%80%9C%E7%B1%BB%E2%80%9D%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F"><span class="nav-number">1.0.1.0.1.</span> <span class="nav-text">4.1.1 “类”设计模式</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-1-2-JavaScript%E4%B8%AD%E7%9A%84%E2%80%9C%E7%B1%BB%E2%80%9D"><span class="nav-number">1.0.1.0.2.</span> <span class="nav-text">4.1.2 JavaScript中的“类”</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-%E7%B1%BB%E7%9A%84%E6%9C%BA%E5%88%B6"><span class="nav-number">1.0.2.</span> <span class="nav-text">4.2 类的机制</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-1-%E5%BB%BA%E9%80%A0"><span class="nav-number">1.0.2.0.1.</span> <span class="nav-text">4.2.1 建造</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-2-%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="nav-number">1.0.2.0.2.</span> <span class="nav-text">4.2.2 构造函数</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-%E7%B1%BB%E7%9A%84%E7%BB%A7%E6%89%BF"><span class="nav-number">1.0.3.</span> <span class="nav-text">4.3 类的继承</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#4-3-1-%E5%A4%9A%E6%80%81"><span class="nav-number">1.0.3.0.1.</span> <span class="nav-text">4.3.1 多态</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-3-2-%E5%A4%9A%E9%87%8D%E7%BB%A7%E6%89%BF"><span class="nav-number">1.0.3.0.2.</span> <span class="nav-text">4.3.2 多重继承</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-%E6%B7%B7%E5%85%A5"><span class="nav-number">1.0.4.</span> <span class="nav-text">4.4 混入</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#4-4-1-%E6%98%BE%E5%BC%8F%E6%B7%B7%E5%85%A5"><span class="nav-number">1.0.4.0.1.</span> <span class="nav-text">4.4.1 显式混入</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-4-2-%E9%9A%90%E5%BC%8F%E6%B7%B7%E5%85%A5"><span class="nav-number">1.0.4.0.2.</span> <span class="nav-text">4.4.2 隐式混入</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-5-%E5%B0%8F%E7%BB%93"><span class="nav-number">1.0.5.</span> <span class="nav-text">4.5 小结</span></a></li></ol></li></ol></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E04/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          《你不知道的JavaScript(上)》S02E04
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2020-12-01 22:26:46 / 修改时间：23:07:14" itemprop="dateCreated datePublished" datetime="2020-12-01T22:26:46+08:00">2020-12-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/%E4%B8%80%E5%91%A8%E4%B8%80%E7%AB%A0%E5%89%8D%E7%AB%AF%E4%B9%A6/" itemprop="url" rel="index"><span itemprop="name">一周一章前端书</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>4.7k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>4 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="第4章-：混合对象“类”"><a href="#第4章-：混合对象“类”" class="headerlink" title="第4章 ：混合对象“类”"></a>第4章 ：混合对象“类”</h1><ul>
<li>本章要介绍和类相关的面相对象编程的知识。首先会介绍面相对象类的设计模式：实例化(instantiation)、继承(inheritance)、多态(polymorphism)。</li>
<li>但由于这些概念上无法直接对应到JavaScript的对象机制，因此很多JavaScript开发者使用了一些比如mixin等解决方法来实现。<h3 id="4-1-类理论"><a href="#4-1-类理论" class="headerlink" title="4.1 类理论"></a>4.1 类理论</h3></li>
<li>类/继承，或者说面向对象，是用来描述代码的一种组织结构形式，它是一种软件对真实世界的建模方法。</li>
<li>面向对象编程强调的是数据和操作数据的行为，本质是是相互关联的。因此，面相对象编程推崇的是，把数据以及和它相关的行为封装起来。这在正式的计算机科学中被称为数据结构。</li>
<li>举例：我们在编程中要描述一个数据，然后我们会定义一个变量，这个值是一个字符串，这也就是数据。但我们在使用的过程之，往往关心的不是数据是什么，而是可以对数据做什么，也就是应用再数据上的行为（比如计算数据长度啊、追加数据啊、搜索数据中的字符啊等等）。因此这些行为被设计成了String类。</li>
<li>再来看一个例子：“汽车”可以被看做“交通工具”的一种，对于这种关系，我们在软件中可以定义Vehicle类和Car类来进行建模。</li>
<li>Vehicle类的定义，可能包含推进器(比如引擎)、载人能力等。它包含所有类型的交通工具，不管是飞机、汽车或者火车。</li>
<li>而Car类继承了Vehicle类，以通用的Vehicle类作为基础进行特殊化定义，比如加上汽车的车辆识别码等。</li>
<li>虽然Vehicle和Car会定义相同的方法，但实例中的数据可能是不同的，这就是类、继承和实例化。</li>
<li>类的另一个核心概念是多态，是说父类的通用行为可以被子类用更特殊的行为进行重写。</li>
</ul>
<h5 id="4-1-1-“类”设计模式"><a href="#4-1-1-“类”设计模式" class="headerlink" title="4.1.1 “类”设计模式"></a>4.1.1 “类”设计模式</h5><ul>
<li>有人可能从来没把类作为设计模式来看，反而更熟悉的是比如观察者模式、工厂模式、单例模式等其他模式。但是这些高级设计模式，都以面向对象类的基础上实现的。</li>
<li>可能你还听过“过程化编程”，这种代码只包含过程调用，没有高层的抽象。</li>
<li>除此之外，如果有函数式编程的开发经验，会知道类也是非常常用的设计模式，但类不是必须的编程基础，而是一种可选的代码抽象。而在其他编程语言比如Java中，并不给你选择的机会，万物皆对象。</li>
</ul>
<h5 id="4-1-2-JavaScript中的“类”"><a href="#4-1-2-JavaScript中的“类”" class="headerlink" title="4.1.2 JavaScript中的“类”"></a>4.1.2 JavaScript中的“类”</h5><ul>
<li>在软件设计中，类是一种可选的模式。由于许多开发者都非常喜欢面向类的软件设计，JavaScript提供了语法糖来满足对于类设计模式的最普片需求，比如ES6新增了比如class关键字等，但javascript中的“类”和和其他语言中的类并不一样。</li>
</ul>
<h3 id="4-2-类的机制"><a href="#4-2-类的机制" class="headerlink" title="4.2 类的机制"></a>4.2 类的机制</h3><ul>
<li>在许多面向类的语言中，内置会提供Stack类，这是一种“栈”数据结构，同时会提供一些公有的方法。但实际上我们并不是直接操作Stack，Stack类仅仅是一个抽象的表示，它本身并不是一个“栈”。使用的时候，通常也需要先实例化Stack类，然后才能对它进行操作。<h5 id="4-2-1-建造"><a href="#4-2-1-建造" class="headerlink" title="4.2.1 建造"></a>4.2.1 建造</h5></li>
<li>类和实例的概念源于房屋建造。<ol>
<li>在建造之前，建筑师通常会规划一个建造蓝图来描绘建筑的特性：宽、高、几室几厅、多少个窗户以及窗户的位置等。但在这个阶段，并不关心建筑会被建在哪，也不关心会建造多少个这样的建筑，甚至不用关心建筑中的内容（比如家具、壁纸、吊灯等）。建筑蓝图只是建筑计划，它们并不是真正的建筑。</li>
<li>接下来，需要一个建筑工人按照蓝图建造建筑，把规划好的特性从蓝图中复制到现实世界的建筑中。</li>
<li>完成后，建筑就成为了蓝图的物理实例。如果需要建筑多套房子，只需把工作都重复一遍，再创建一份副本。</li>
</ol>
</li>
<li>建筑和蓝图之间的关系是间接的。蓝图只是抽象描绘了建筑的结构，比如蓝图只表示门在哪，但并不是真正的门，如果想打开一扇门，那就必须接触真实的建筑才行。</li>
<li>一个类就是一张建造蓝图，为了获得真正的建筑，我们必须按照类来建造(实例化)一个东西，而这个东西通常被称为实例。</li>
</ul>
<h5 id="4-2-2-构造函数"><a href="#4-2-2-构造函数" class="headerlink" title="4.2.2 构造函数"></a>4.2.2 构造函数</h5><ul>
<li>实例是由一个特殊的类方法构造的，这个类方法的方法名通常和类名相同，称为构造函数。</li>
<li>构造函数大多情况下，需要用<code>new</code>来调用，构造函数的主要任务，就是初始化实例需要的所有信息。</li>
</ul>
<h3 id="4-3-类的继承"><a href="#4-3-类的继承" class="headerlink" title="4.3 类的继承"></a>4.3 类的继承</h3><ul>
<li>在面向类的语言中，当一个类继承另一个类时。后者通常被称为“子类”，前者会被称为“父类”。</li>
<li>从术语来看，显然是类比父母和孩子。在现实中，孩子会从父母继承许多基因特性，但通常孩子不会和父母一模一样，即便外貌长相会类似，但性格行为却大不相同，因为孩子是一个独一无二的存在。</li>
<li>同理，在程序中，相对于父类来说，子类也是一个独立个体。子类会包含父类行为的原始副本，但也可以重写所有继承的行为甚至定义新的行为。<blockquote>
<p>注意：有必要说明一下，这里说的父类和子类不是实例，而是像上文说得建造蓝图一样。我们应当把父类和子类称为父类DNA和子类DNA，需要根据这些DNA来创建(实例化)一个人，我们才拥有一个真实的实例。</p>
</blockquote>
</li>
</ul>
<h5 id="4-3-1-多态"><a href="#4-3-1-多态" class="headerlink" title="4.3.1 多态"></a>4.3.1 多态</h5><ul>
<li>当子类继承父类，引用父类原始的方法时，这里被称为多态（相对多态）。<blockquote>
<p>说明：实际上多态是任何方法都能引用继承层级中上层的类的方法。之所以说是“相对”，是因为当前子类引用的是父类的方法，而实际上还可以引用祖先类(superclass)的方法。</p>
</blockquote>
</li>
<li>多态并不表示子类和父类有关联，子类得到的只是父类的一个副本。类的继承其实就是复制。</li>
</ul>
<h5 id="4-3-2-多重继承"><a href="#4-3-2-多重继承" class="headerlink" title="4.3.2 多重继承"></a>4.3.2 多重继承</h5><ul>
<li>有些面向类的语言允许子类继承多个“父类”，多重继承意味着所有父类的定义都会被复制到子类中。</li>
<li>从表面看，多继承可以把许多功能组合在一起。然而这个机制也会带来很多复杂的问题。比如，当子类调用两个父类同名的方法时，就不知道该怎么处理了。</li>
<li>JavaScript本身也不提供“多重继承”功能，但也可以用各种办法来实现多重继承。</li>
</ul>
<h3 id="4-4-混入"><a href="#4-4-混入" class="headerlink" title="4.4 混入"></a>4.4 混入</h3><ul>
<li>在继承或实例化时，JavaScript的对象机制并不会自动执行复制行为。换句话说，JavaScript中只有对象，不存在可以被实例化的“类”。不会复制对象，它们只是被关联起来。</li>
<li>由于在其他语言中，类表现出来的都是复制行为，因此JavaScript开发者也想出了一个方法来模拟类的复制行为，就是混入。</li>
<li>有两种类型的混入：显式和隐式。<h5 id="4-4-1-显式混入"><a href="#4-4-1-显式混入" class="headerlink" title="4.4.1 显式混入"></a>4.4.1 显式混入</h5></li>
<li>之前提到的Vehicle和Car。接下来，我们用JavaScript手动实现复制功能。这个功能在许多库和框架中被称为<code>extend()</code>，但是为了方便理解我们称之为<code>minxin()</code>：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">minxin</span>(<span class="params">sourceOBj,targetObj</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> key <span class="keyword">in</span> sourceObj)&#123;</span><br><span class="line">        <span class="keyword">if</span>(!(key <span class="keyword">in</span> targetObj))&#123;</span><br><span class="line">            targetObj[key] = sourceObj[key];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> targetObj;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> Vehicle = &#123;</span><br><span class="line">    engines : <span class="number">1</span>,</span><br><span class="line">    ignition: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Turning on my engine.&#x27;</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">    drive : <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.ignition();</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Steering and moving forward!&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">var</span> Car = mixin(Vehicle,&#123;</span><br><span class="line">    wheels : <span class="number">4</span>,</span><br><span class="line">    drive : <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        Vehicle.drive.call(<span class="built_in">this</span>);</span><br><span class="line">        <span class="built_in">console</span>.log(</span><br><span class="line">            <span class="string">&#x27;Rolling on all&#x27;</span> + <span class="built_in">this</span>.wheels + <span class="string">&#x27; wheels!&#x27;</span></span><br><span class="line">        );</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></li>
<li>Car中就拥有一份Vehicle属性和函数的副本了，但注意：复制的是函数的引用。</li>
<li>再说多态：<code>Vehicle.drive.call(this)</code>就是显示多态，清楚证明调用的是父类还是祖先类；<code>inherited:drive()</code>就是相对多态。</li>
<li>mixin()的工作原理：它会遍历sourceObj的属性，如果在targetObj没有这个属性就会进行复制。</li>
<li>显式混入模式的另一种变体被称为“寄生继承”：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Vehicle</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.engines = <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line">Vehicle.prototype.ignition = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Turning on my engine.&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line">Vehicle.prototype.drive = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.ignition();</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;Steering and moving forward!&#x27;</span>);</span><br><span class="line">&#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Car</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> car = <span class="keyword">new</span> Vehicle();</span><br><span class="line">    car.wheels = <span class="number">4</span>;</span><br><span class="line">    <span class="keyword">var</span> vehDrive = car.drive;</span><br><span class="line">    car.drive = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        vehDrive.call(<span class="built_in">this</span>);</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Rolling on all &#x27;</span> + <span class="built_in">this</span>.wheels + <span class="string">&#x27; wheels!&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> car;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> myCar = <span class="keyword">new</span> Car();</span><br><span class="line">myCar.drive();</span><br></pre></td></tr></table></figure>
<h5 id="4-4-2-隐式混入"><a href="#4-4-2-隐式混入" class="headerlink" title="4.4.2 隐式混入"></a>4.4.2 隐式混入</h5></li>
<li>隐式混入和显式伪多态很像，但同样拥有同样的问题：不是真正的对象复制，而是复制引用。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Something = &#123;</span><br><span class="line">    cool : <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.greeting = <span class="string">&#x27;Hello World!&#x27;</span></span><br><span class="line">        <span class="built_in">this</span>.count = <span class="built_in">this</span>.count ? <span class="built_in">this</span>.count + <span class="number">1</span> : <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">Something.cool();</span><br><span class="line">Something.greeting; <span class="comment">//&#x27;Hello World&#x27;</span></span><br><span class="line">Something.count;    <span class="comment">//1</span></span><br><span class="line">Another = &#123;</span><br><span class="line">    cool : <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        Something.cool.call(<span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">Another.cool();</span><br><span class="line">Another.greeting;   <span class="comment">// &#x27;Hello World&#x27;</span></span><br><span class="line">Another.count;  <span class="comment">// 1</span></span><br></pre></td></tr></table></figure></li>
<li>如果在构造函数调用使用<code>Something.cool.call(this)</code>，最终的结果是<code>Something.cool()</code>中的赋值操作都会应用再Another对象上而不是Something对象上。</li>
<li>通常来说，应该尽量避免使用这一的结构，以保证代码的整洁和可维护性。</li>
</ul>
<h3 id="4-5-小结"><a href="#4-5-小结" class="headerlink" title="4.5 小结"></a>4.5 小结</h3><ul>
<li>类是一种设计模式，许多语言提供了面向类软件设计的原生语法。JavaScript也有类似的语法，但和其他语言中的类完全不同。</li>
<li>类意味着复制。传统的类被实例化的时候，它的行为会被复制到实例中。类被继承时，行为也会被复制到子类中。</li>
<li>多态看起来似乎是从子类引用父类，但本质上引用的其实是复制的结果。</li>
<li>JavaScript不会像类那样自动创建对象的副本。但通过混入模式可以模拟类的复制行为，但通常会产生丑陋且脆弱的语法，这会让代码更加难懂并且难以维护。</li>
<li>显式混入实际上无法完全模拟类的复制行为，因为对象只是复制引用，无法复制被引用的对象或者函数本身。</li>
<li>总的来说，在JavaScript中模拟类是得不偿失的，可能会买下更多隐患。</li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>William Leung
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E04/" title="《你不知道的JavaScript(上)》S02E04">https://gitee.com/lianghuilin/murmur.git/reading_notes/《你不知道的JavaScript-上-》S02E04/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/murmur/tags/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript/" rel="tag"># 你不知道的JavaScript</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E03/" rel="prev" title="《你不知道的JavaScript(上)》S02E03">
                  <i class="fa fa-chevron-left"></i> 《你不知道的JavaScript(上)》S02E03
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS02E05/" rel="next" title="《你不知道的JavaScript(上)》S02E05">
                  《你不知道的JavaScript(上)》S02E05 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
